"""
模板配置数据模型
定义PPT模板的配置结构，包括颜色方案、字体配置和布局设置。
"""

from pydantic import BaseModel, Field, validator
from typing import Dict, List, Optional, Any, Union
from enum import Enum


class FontWeight(str, Enum):
    """字体粗细枚举"""
    NORMAL = "normal"
    BOLD = "bold"
    LIGHT = "light"


class TextAlignment(str, Enum):
    """文本对齐方式枚举"""
    LEFT = "left"
    CENTER = "center"
    RIGHT = "right"
    JUSTIFY = "justify"


class LayoutType(str, Enum):
    """布局类型枚举"""
    TITLE_SLIDE = "title_slide"
    CONTENT_SLIDE = "content_slide"
    TWO_COLUMN = "two_column"
    IMAGE_SLIDE = "image_slide"
    CHART_SLIDE = "chart_slide"
    BLANK_SLIDE = "blank_slide"


class ColorScheme(BaseModel):
    """颜色方案配置"""
    
    primary: str = Field(..., description="主色调")
    secondary: str = Field(..., description="辅助色")
    accent: str = Field(..., description="强调色")
    background: str = Field(default="#FFFFFF", description="背景色")
    text_primary: str = Field(default="#333333", description="主要文本色")
    text_secondary: str = Field(default="#666666", description="次要文本色")
    border: str = Field(default="#E0E0E0", description="边框色")
    
    @validator('primary', 'secondary', 'accent', 'background', 'text_primary', 'text_secondary', 'border')
    def validate_color_format(cls, v):
        """验证颜色格式"""
        if not v.startswith('#') or len(v) != 7:
            raise ValueError('颜色必须是7位十六进制格式，如 #FFFFFF')
        try:
            int(v[1:], 16)
        except ValueError:
            raise ValueError('无效的十六进制颜色值')
        return v.upper()


class FontConfig(BaseModel):
    """字体配置"""
    
    family: str = Field(..., description="字体族")
    size: int = Field(..., ge=8, le=72, description="字体大小")
    weight: FontWeight = Field(default=FontWeight.NORMAL, description="字体粗细")
    color: str = Field(default="#333333", description="字体颜色")
    
    @validator('color')
    def validate_font_color(cls, v):
        """验证字体颜色格式"""
        if not v.startswith('#') or len(v) != 7:
            raise ValueError('颜色必须是7位十六进制格式，如 #FFFFFF')
        return v.upper()


class LayoutConfig(BaseModel):
    """布局配置"""
    
    type: LayoutType = Field(..., description="布局类型")
    margins: Dict[str, int] = Field(
        default={"top": 50, "bottom": 50, "left": 50, "right": 50},
        description="页边距配置"
    )
    spacing: Dict[str, int] = Field(
        default={"line": 20, "paragraph": 30},
        description="间距配置"
    )
    content_area: Dict[str, Union[int, float]] = Field(
        default={"x": 0.1, "y": 0.15, "width": 0.8, "height": 0.7},
        description="内容区域配置（相对位置）"
    )
    
    @validator('margins')
    def validate_margins(cls, v):
        """验证页边距配置"""
        required_keys = ['top', 'bottom', 'left', 'right']
        for key in required_keys:
            if key not in v:
                raise ValueError(f'页边距配置缺少 {key} 参数')
            if not isinstance(v[key], int) or v[key] < 0:
                raise ValueError(f'页边距 {key} 必须是非负整数')
        return v


class TemplateStyle(BaseModel):
    """模板样式配置"""
    
    name: str = Field(..., description="样式名称")
    display_name: str = Field(..., description="显示名称")
    description: str = Field(..., description="样式描述")
    
    # 颜色方案
    color_scheme: ColorScheme = Field(..., description="颜色方案")
    
    # 字体配置
    fonts: Dict[str, FontConfig] = Field(..., description="字体配置")
    
    # 布局配置
    layouts: Dict[str, LayoutConfig] = Field(..., description="布局配置")
    
    # 其他样式属性
    border_radius: int = Field(default=0, ge=0, description="圆角半径")
    shadow_enabled: bool = Field(default=False, description="是否启用阴影")
    animation_enabled: bool = Field(default=False, description="是否启用动画")
    
    @validator('fonts')
    def validate_fonts(cls, v):
        """验证字体配置"""
        required_font_types = ['title', 'heading', 'body', 'caption']
        for font_type in required_font_types:
            if font_type not in v:
                raise ValueError(f'字体配置缺少 {font_type} 类型')
        return v
    
    @validator('layouts')
    def validate_layouts(cls, v):
        """验证布局配置"""
        required_layouts = ['title_slide', 'content_slide']
        for layout_type in required_layouts:
            if layout_type not in v:
                raise ValueError(f'布局配置缺少 {layout_type} 类型')
        return v


class TemplateMetadata(BaseModel):
    """模板元数据"""
    
    id: str = Field(..., description="模板ID")
    name: str = Field(..., description="模板名称")
    category: str = Field(..., description="模板分类")
    tags: List[str] = Field(default_factory=list, description="模板标签")
    author: str = Field(default="系统", description="模板作者")
    version: str = Field(default="1.0.0", description="模板版本")
    created_at: str = Field(..., description="创建时间")
    updated_at: str = Field(..., description="更新时间")
    is_active: bool = Field(default=True, description="是否激活")
    preview_image: Optional[str] = Field(None, description="预览图片路径")


class TemplateConfig(BaseModel):
    """完整的模板配置"""
    
    metadata: TemplateMetadata = Field(..., description="模板元数据")
    style: TemplateStyle = Field(..., description="模板样式")
    
    class Config:
        """Pydantic配置"""
        json_schema_extra = {
            "example": {
                "metadata": {
                    "id": "professional_blue",
                    "name": "专业蓝色",
                    "category": "商务",
                    "tags": ["专业", "商务", "蓝色"],
                    "author": "系统",
                    "version": "1.0.0",
                    "created_at": "2024-01-01T00:00:00",
                    "updated_at": "2024-01-01T00:00:00",
                    "is_active": True
                },
                "style": {
                    "name": "professional",
                    "display_name": "专业风格",
                    "description": "适合商务演示的专业风格模板",
                    "color_scheme": {
                        "primary": "#2E86AB",
                        "secondary": "#A23B72",
                        "accent": "#F18F01",
                        "background": "#FFFFFF",
                        "text_primary": "#333333",
                        "text_secondary": "#666666",
                        "border": "#E0E0E0"
                    },
                    "fonts": {
                        "title": {
                            "family": "Microsoft YaHei",
                            "size": 32,
                            "weight": "bold",
                            "color": "#2E86AB"
                        },
                        "heading": {
                            "family": "Microsoft YaHei",
                            "size": 24,
                            "weight": "bold",
                            "color": "#333333"
                        },
                        "body": {
                            "family": "Microsoft YaHei",
                            "size": 16,
                            "weight": "normal",
                            "color": "#333333"
                        },
                        "caption": {
                            "family": "Microsoft YaHei",
                            "size": 12,
                            "weight": "normal",
                            "color": "#666666"
                        }
                    },
                    "layouts": {
                        "title_slide": {
                            "type": "title_slide",
                            "margins": {"top": 80, "bottom": 80, "left": 60, "right": 60},
                            "spacing": {"line": 25, "paragraph": 40},
                            "content_area": {"x": 0.1, "y": 0.2, "width": 0.8, "height": 0.6}
                        },
                        "content_slide": {
                            "type": "content_slide",
                            "margins": {"top": 60, "bottom": 60, "left": 50, "right": 50},
                            "spacing": {"line": 20, "paragraph": 30},
                            "content_area": {"x": 0.1, "y": 0.15, "width": 0.8, "height": 0.7}
                        }
                    },
                    "border_radius": 5,
                    "shadow_enabled": True,
                    "animation_enabled": False
                }
            }
        }